package NetWork;
import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class MyUDPClient {
    //创建socket，用于发送和接收数据报
    private DatagramSocket socket;
    String serverIp;
    int serverPort;
    public MyUDPClient(String serverIp,int serverPort) throws SocketException {
        //客户端不用指定端口号（随机绑定）
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    //启动客户端和内部逻辑
    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        while(true) {
            //1，客户端发送请求
            System.out.println("->");
            String request = in.nextLine();
            //2，将请求转换为数据报发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    request.getBytes(StandardCharsets.UTF_8).length,InetAddress.getByName(serverIp),serverPort);
            //3，发送数据报给服务器
            socket.send(requestPacket);
            //4，接收服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4090],4090);
            socket.receive(responsePacket);
            //5，将响应转成字符串，回显客户端
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //日志
            System.out.printf("req: %s,resp: %s\n",request,response);
        }
    }

    public static void main(String[] args) throws IOException {
        MyUDPClient myUDPClient = new MyUDPClient("127.0.0.1",6666);
        myUDPClient.start();
    }
}

